# app.py
from flask import Flask, request, jsonify, render_template
from deepseek_api import DeepSeekAPI
import os

app = Flask(__name__)

# 初始化DeepSeek API客户端
api_client = DeepSeekAPI(
    api_key='API_KEY',
    api_url='API_URL',
    model='MODEL'
)

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/api/generate', methods=['POST'])
def generate_content():
    """生成内容接口"""
    try:
        data = request.get_json()
        action = data.get('action', 'chat')
        topic = data.get('topic', '').strip()
        text = data.get('text', '')
        style = data.get('style', '正式')
        length = data.get('length', '中等')
        improvement_type = data.get('improvement_type', '语法优化')
        
        if not topic and not text:
            return jsonify({'error': '内容不能为空'}), 400
        
        # 根据动作类型调用不同方法
        if action == 'generate_article':
            result = api_client.generate_article(topic, style, length)
        elif action == 'improve_writing':
            result = api_client.improve_writing(text, improvement_type)
        elif action == 'generate_outline':
            result = api_client.generate_outline(topic)
        else:
            # 普通聊天
            messages = [{"role": "user", "content": topic}]
            result = api_client.chat_completion(messages)
        
        return jsonify({
            'success': True,
            'result': result,
            'action': action
        })
        
    except Exception as e:
        return jsonify({'error': f'生成失败: {str(e)}'}), 500

if __name__ == '__main__':
    # 创建模板目录
    os.makedirs('templates', exist_ok=True)
    
    print("=" * 50)
    print("智能写作助手启动成功!")
    print("访问: http://localhost:5000")
    print("=" * 50)
    
    app.run(debug=True, host='0.0.0.0', port=5000)